<?php
namespace app\home\controller;
use app\common\controller\HomeBase;
use app\common\model\Weibo;
use think\Request;
use think\Session;
use Gregwar\Image\Image;//使用composer依赖的第三方扩展包 图像处理
/**
 * 首页控制器
 * 继承了前台控制器 可以直接使用 View视图类, Request请求类
 * Class Index
 * @package app\home\controller
 */
class Index extends HomeBase{
    public function index () {
        $weiboModel = new \app\common\model\Weibo();
        $where1 = ['fans' => session('uid')];
        $gid = Request::instance()->param('gid');
        if (isset($gid)) {
            $where1['gid'] = $gid;
            $uids = [];
        }
        $relust = db('follow')->field('follow')->where($where1)->select();

        if ($relust) {
            foreach ($relust as $v) {
                $uids[] = $v['follow'];
            }
        }
        if ($uids && !$gid) {
            $uids[] = session('uid');
        } else {
            $uids[] = 0;
        }
        $where = ['w.uid' => ['in',$uids]];
        return $this->fetch('index',['data'=>$weiboModel->getListData($where)]);
    }

    // 微博收藏
    public function keep() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $wid = $request->post('wid');
            $db = db('Keep');
            $uid = Session::get('uid');
            if ($db->where(['wid'=>$wid,'uid'=> $uid])->value('id')) {
                return ['status'=>'-1'];
            }
            $data = [
                'uid' => $uid,
                'time' => time(),
                'wid' => $wid
            ];
            if ($db->insert($data)) {
                return ['status' => 1];
            } else {
                return ['status' => 0];
            }
        }
    }



    /**
     * 创建分组
     */
    public function add_group() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $group_name = $request->post('name');
            $data = [
                'name' => trim($group_name),
                'uid'  => Session::get('uid')
            ];

            // Db::table() 类返回的是数组 而且 model('User') 实例化模型 是返回对象实例
            // db()方法 跟 3.2.3 M() 一样 实例化数据类 insert 返回的是记录数
            if ($id = db('Group')->insertGetId($data)) {
                $str =<<<str
            <li>
                <a href=""><i class='icon icon-group'></i>&nbsp;{$group_name}</a>
            </li>
str;
                return ['status' => 1,'msg' => '添加成功.^_^','add_msg' => $str];
            } else {
                return ['status' => 0,'msg' => '系统错误,请重试...'];
            }
        }
    }

    /**
     * 发布微博
     */
    public function send_weibo() {
        $request = Request::instance();
        if ($request->isAjax()) {
            $data = [
                'content' => $request->post('content'),
                'time' => time(),
                'uid' => Session::get('uid')
            ];

            if  ($wid = db('Weibo')->insertGetId($data)) {
                if (!empty($request->post('max'))) {
                    $img_data = [
                        'max' => $request->post('max'),
                        'mini' => $request->post('mini'),
                        'medium' => $request->post('medium'),
                        'img' => $request->post('img'),
                        'wid' => $wid
                    ];
                    db('Picture')->insert($img_data);
                }
                db('Userinfo')->where(['uid'=>Session::get('uid')])->setInc('weibo');

                //处理@用户
                $this->_atmeHandel($data['content'],$wid);
                return ['status'=>1,'url' => $_SERVER['HTTP_REFERER'],'msg' => '发布成功.^_^'];
            } else {
                return ['status'=>0,'msg' => '发布失败,请重试...'];
            }
        }
    }


    /**
     * @用户处理
     */
    private function _atmeHandel ($content,$wid) {
        $preg = '/@(\S+?)\s/is';
        preg_match_all($preg,$content,$arr);
        if ($arr[1]) {
            $db = db('Userinfo');
            foreach ($arr[1] as $v) {
                $uid = $db->where(['username' => $v])->value('uid');
                if ($uid) {
                    $data = [
                        'wid' => $wid,
                        'uid' => $uid
                    ];
                    db('Atme')->insert($data);
                }
            }
        }
    }

    /**
     *  上传微博图片
     */
    public function uploadify_weibo() {
        //获取表单上传文件
        $file = Request::instance()->file('Filedata');
        // 上传文件验证
        $validate_img = [
            'ext'  => 'jpg,png,jpeg,gif',//允许上传的文件后缀 [数组|字符串]
            'size' => 3145728,//上传文件最大字节大小
        ];
        $info = $file->rule('date')->validate($validate_img)->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'weibo');
        if ($info) {
            // 获取上传后文件名  $info->getSaveName()
            $roorImg = '/uploads/weibo/' . $info->getSaveName();
            // 替换转义符重组新的全路径 $info->getSaveName() 获取的值为 20160923\f7bbac26c.jpg 需要替换转义字符
            $img = str_replace("\\","/",$roorImg);
            // 图片裁剪
//            $image = \think\Image::open("." . $img);
            $image = Image::open("." . $img);//composer第三方扩展包
            // 获取上传后文件目录
            $dir = explode("/",str_replace("\\","/",$info->getSaveName()));
            $data = [
                'face_120' => "." . '/uploads/weibo/' . $dir[0] . "/" . "mini_" . $dir[1],
                'face_380' => "." . '/uploads/weibo/' . $dir[0] . "/" . "middle_" . $dir[1],
                'face_880' => "." . '/uploads/weibo/' . $dir[0] . "/" . "max_" . $dir[1],
            ];
            // 按照原图的比例生成缩略图 居中生成
//            $image->thumb(120,120,\think\Image::THUMB_CENTER)->save($data['face_120']);
//            $image->thumb(380,380,\think\Image::THUMB_CENTER)->save($data['face_380']);
//            $image->thumb(800,800,\think\Image::THUMB_CENTER)->save($data['face_880']);
            $image->forceResize(800,800)->save($data['face_880']);
            $image->forceResize(380,380)->save($data['face_380']);
            $image->forceResize(120,120)->save($data['face_120']);
            $returnData = [
                'face120' => '/uploads/weibo/' . $dir[0] . "/" . "mini_" . $dir[1],
                'face380' => '/uploads/weibo/' . $dir[0] . "/" . "middle_" . $dir[1],
                'face880' => '/uploads/weibo/' . $dir[0] . "/" . "max_" . $dir[1],
                'face' => $img
            ];
            return json(['status' => 1,'info' => $returnData]);

        } else {
            // 获取文件上传错误信息 $file->getError()
            return json(['status'=>0,'msg'=>$file->getError()]);
        }
    }

    //好友关注
    public function follow() {
        if (Request()->isAjax()) {
            $follow = input('post.follow');
            $gid = input('post.gid');
            $userinfo_id = input('post.userinfo_id');
            $type = input('post.type');
            if (!$follow) return ['status'=>0,'msg'=>'参数错误,请重试...'];
            $data = [
                'follow' => $follow,
                'fans' => Session::get('uid'),
                'gid' => $gid
            ];
            $url = url('home/index/del_follow');
            if (db('follow')->insert($data)) {
                db('userinfo')->where(['uid'=>$follow])->setInc('fans');
                db('userinfo')->where(['uid'=>Session::get('uid')])->setInc('follow');
                if ($type) {
                $str=<<<str
                <span class="heed_btn" style="width:60px;">√<span style="margin-left: 5px;">已关注</span></span>
str;
                } else {
                $str=<<<str
                 <dt>√<span style="margin-left: 5px;">已关注</span></dt>
                 <dd class='del-follow' fid="{$follow}" oid="{$userinfo_id}" url="{$url}">移除</dd>
str;
                }
                return ['status'=>1,'msg'=>$str];
            } else {
                return ['status'=>0,'msg'=>'关注失败.ㄒoㄒ~'];
            }
        }
    }

    //移除关注
    public function del_follow() {
        if (Request()->isAjax()) {
            $follow = input('post.fid');
            $oid = input('post.ids');
            if (!$follow) return ['status'=>0,'msg'=>'参数错误,请重试...'];
            if (db('follow')->where(['follow'=>$follow,'fans'=>Session::get('uid')])->delete()) {
                db('userinfo')->where(['uid'=>$follow])->setDec('fans');
                db('userinfo')->where(['uid'=>Session::get('uid')])->setDec('follow');
                $str=<<<str
                <dt class='add-fl' uid="{$follow}" oid="{$oid}">+<span style="margin-left: 5px;">关注</span></dt>
str;
                return ['status'=>1,'msg'=> $str];
            } else {
                return ['status'=>0,'msg' => '移除失败.ㄒoㄒ~'];
            }
        }
    }

    /**
     * 删除微博
     */
    public function del_weibo() {
        if (Request::instance()->isAjax()) {
            $wid = input('post.wid',0,'intval');
            if (!$wid) return ['status'=>0,'msg'=>'参数错误,请重试...'];
            if (Weibo::destroy($wid)) {
                $data = db('picture')->where(['wid'=>$wid])->find();
                if ($data) {
                    unlink("." . $data['mini']);
                    unlink("." . $data['medium']);
                    unlink("." . $data['max']);
                    db('picture')->where(['wid'=>$wid])->delete();
                }
                return ['status'=>1,'msg'=>'删除成功.^_^'];
            } else {
                return ['status'=>0,'msg'=>'删除失败,请重试...'];
            }
        }
    }

    /**
     * 点赞
     */
    public function praise() {
        if (Request()->isAjax()) {
            $wid = input('post.wid',0,'int');
            $db = db('praise');
            if (!$wid) return ['status'=>0,'msg'=>'参数错误,请重试...'];
            $data = [
                'wid' => $wid,
                'uid' =>Session::get('uid'),
                'time' => time()
            ];
            if ($db->where(['wid'=>$wid,'uid'=>Session::get('uid')])->value('id')) {
                return ['status'=>2,'msg'=>'已经点过赞了.^_^'];
            }
            if (db('praise')->insert($data)) {
                db('weibo')->where(['id'=>$wid])->setInc('praise');
                return ['status'=>1,'msg'=>'点赞成功.^_^'];
            } else {
                return ['status'=>0,'msg'=>'系统错误,请重试...'];
            }
        }
    }
}
